package com.yang.my.sync.six;

/**
 * 对象锁
 *
 * @Author: Mu_YI
 * @Date: 2019/3/17 21:27
 * @Version 1.0
 */
public class ObjectLock {

    private void methodOne() {
        // 对象锁
        synchronized (this) {
            try {
                System.out.println("do method1....");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void methodTwo() {
        // 类锁
        synchronized (ObjectLock.class) {
            try {
                System.out.println("do method2....");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    private Object object = new Object();

    private void methodThree() {
        //  任何对象锁
        synchronized (object) {
            try {
                System.out.println("do method3.....");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {

        ObjectLock objectLock = new ObjectLock();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                objectLock.methodOne();
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                objectLock.methodTwo();
            }
        });

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                objectLock.methodThree();
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
